from fdfs_client.client import Fdfs_client
client = Fdfs_client("utils/fastdfs/client.conf")


def upload(buffer, file_ext_name, conf="utils/fastdfs/client.conf"):
    from fdfs_client.client import Fdfs_client
    from dj32_test.settings.dev import FDFS_DOMAIN
    try:
        client = Fdfs_client(conf)
    except Exception as e:
        print("配置文件错误：", e)

    response = client.upload_by_buffer(buffer, file_ext_name)
    if "successed" in response.get("Status"):
        # FDFS_DOMAIn:你的fdfs文件存储访问域名
        return FDFS_DOMAIN + response.get("Remote file_id")
    else:
        raise Exception("文件上传失败")


if __name__ == '__main__':
    filename = "dj_2.jpg"
    try:
        with open(filename, "rb") as fp:
            data = fp.read()
            ext = filename.split(".")[-1]
            access_url = upload(data, file_ext_name=ext)
    except Exception as e:
        print(e)
    else:
        print(access_url)